<template>
  <div class="question-page">
    <a-card class="card">
      <a-page-header
        title="编辑答题应用题目"
        @back="router.back"
      >
        <template #extra>
          <a-button type="primary" @click="scrollToBottom">前往底部</a-button>
        </template>
      </a-page-header>
      <div class="app-info">
        <p>应用名称：{{ appInfo.appName }}</p>
        <p>应用类别：{{ appInfo.appCategory }}</p>
      </div>
      <a-form :model="formData">
        <a-card
          v-for="(question, qIndex) in formData.questions"
          :key="qIndex"
          class="question-card"
          :title="`题目 ${qIndex + 1}`"
        >
          <a-space direction="vertical" fill>
            <a-form-item>
              <a-textarea
                v-model:value="question.title"
                placeholder="请输入题目具体问题"
                allow-clear
                style="width: 100%"
                :maxlength="200"
                showlimit
              />
            </a-form-item>

            <div v-for="(option, oIndex) in question.options" :key="oIndex" class="option-item">
              <div class="option-header">选项 {{ oIndex + 1 }}</div>
              <a-space direction="vertical" fill style="width: 100%">
                <a-space direction="vertical" fill style="width: 100%">
                  <a-input
                    v-model:value="option.key"
                    placeholder="请输入选项(A,B,C...)"
                    allow-clear
                    style="width: 100%"
                    :maxlength="100"
                    showlimit
                  />
                  <a-input
                    v-model:value="option.value"
                    placeholder="请输入选项内容"
                    allow-clear
                    style="width: 100%"
                    :maxlength="100"
                    showlimit
                  />
                  <a-input
                    v-model:value="option.result"
                    placeholder="选项结果(测评类参考)"
                    allow-clear
                    style="width: 100%"
                    :maxlength="100"
                    showlimit
                  />
                  <a-input-number
                    v-model:value="option.score"
                    placeholder="选项分数(评分类参考)"
                    :min="0"
                    style="width: 100%"
                  />
                </a-space>
                <a-space style="margin-top: 8px">
                  <a-button @click="removeOption(qIndex, oIndex)"  status="warning">
                    删除该选项
                  </a-button>
                  <a-button @click="addOption(qIndex, oIndex)" >在此后添加</a-button>
                </a-space>
              </a-space>
            </div>
          </a-space>

          <template #extra>
            <a-space :size="8">
              <a-button
                size="small"
                @click="addOption(qIndex)"
              >
                添加选项
              </a-button>
              <a-popconfirm
                title="确定要删除该题目吗?"
                @confirm="() => removeQuestion(qIndex)"
                @cancel="() => {}"
              >
                <a-button
                  status="danger"
                  size="small"
                >
                  删除题目
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-card>

        <a-row :gutter="16" style="margin-top: 20px">
          <a-col :span="12">
            <a-button type="primary" long @click="addQuestion">添加题目</a-button>
          </a-col>
          <a-col :span="12">
            <a-button long type="primary" @click="handleSubmit">保存修改</a-button>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import router from "@/router/index.js";
import { queryAppById } from "@/api/app.js";
import { queryQuestionsByAppId, updateQuestion } from "@/api/question.js";
import { message } from 'ant-design-vue';

const appId = ref(0)
const appInfo = ref({})
const formData = ref({
  appId: 0,
  questions: []
})

const getAppId = () => {
  const params = router.currentRoute.value.params
  appId.value = params.id
  formData.value.appId = appId.value
}

const getAppDetail = async () => {
  try {
    const res = await queryAppById(appId.value)
    if (res.data.code === 1) {
      appInfo.value = res.data.data
    }
  } catch (error) {
    console.log(error)
  }
}

const getQuestionDetail = async () => {
  try {
    const res = await queryQuestionsByAppId(appId.value)
    if (res.data.code === 1) {
      let receivedData;
      try {
        receivedData = JSON.parse(res.data.data);
      } catch (e) {
        console.error("Failed to parse data as JSON:", e);
        return;
      }

      // 确保 questions 数组存在并且至少有一个题目
      if (!receivedData.questions || !Array.isArray(receivedData.questions) || receivedData.questions.length < 1) {
        receivedData.questions = [{
          title: '',
          options: [
            { key: '', value: '', result: '', score: null }
          ]
        }];
      }
      formData.value.questions = receivedData;
    }
  } catch (error) {
    console.log(error)
  }
}

// 手动校验函数
const validateForm = () => {
  if (!formData.value.appId) {
    message.error('应用 ID 不能为空');
    return false;
  }
  for (let qIndex = 0; qIndex < formData.value.questions.length; qIndex++) {
    const question = formData.value.questions[qIndex];
    if (!question.title || question.title.length > 200) {
      message.error(`第 ${qIndex + 1} 题的题目标题不能为空且不能超过 200 个字符`);
      return false;
    }
    for (let oIndex = 0; oIndex < question.options.length; oIndex++) {
      const option = question.options[oIndex];
      if (!option.key || option.key.length > 100) {
        message.error(`第 ${qIndex + 1} 题的第 ${oIndex + 1} 个选项不能为空且不能超过 100 个字符`);
        return false;
      }
      if (!option.value || option.value.length > 100) {
        message.error(`第 ${qIndex + 1} 题的第 ${oIndex + 1} 个选项内容不能为空且不能超过 100 个字符`);
        return false;
      }
      if (!option.result || option.result.length > 100) {
        message.error(`第 ${qIndex + 1} 题的第 ${oIndex + 1} 个选项结果不能为空且不能超过 100 个字符`);
        return false;
      }
      if (option.score === null || option.score < 0 || option.score > 10000) {
        message.error(`第 ${qIndex + 1} 题的第 ${oIndex + 1} 个选项分数不能为空且不能超过 10000 分`);
        return false;
      }
    }
  }
  return true;
}

// 添加题目
const addQuestion = () => {
  formData.value.questions.push({
    title: '',
    options: [
      { key: '', value: '', result: '', score: null }
    ]
  })
}

// 删除题目
const removeQuestion = (index) => {
  if (formData.value.questions.length > 1) {
    formData.value.questions.splice(index, 1)
  } else {
    message.warning('至少保留一个题目')
  }
}

// 添加选项
const addOption = (qIndex, insertIndex = null) => {
  const options = formData.value.questions[qIndex].options
  const newOption = {
    key: '',
    value: '',
    result: null,
    score: 0
  }

  if (typeof insertIndex === 'number') {
    options.splice(insertIndex + 1, 0, newOption)
  } else {
    options.push(newOption)
  }
}

// 删除选项
const removeOption = (qIndex, oIndex) => {
  if (formData.value.questions[qIndex].options.length > 1) {
    formData.value.questions[qIndex].options.splice(oIndex, 1)
  } else {
    message.warning('至少保留一个选项')
  }
}

const handleSubmit = async () => {
  if (validateForm()) {
    try {
      const data = {
        appId: formData.value.appId,
        questionContent: formData.value.questions
      }
      const res = await updateQuestion(data)
      if (res.data.code === 1) {
        message.success('题目修改保存成功')
      } else {
        message.error(res.data.message || '保存失败')
      }
    } catch (error) {
      console.error(error)
    }
  }
}

// 滚动到页面底部
const scrollToBottom = () => {
  window.scrollTo({
    top: document.documentElement.scrollHeight,
    behavior: 'smooth' // 平滑滚动
  });
}

onMounted(() => {
  getAppId()
  getAppDetail()
  getQuestionDetail()
})
</script>

<style scoped>
.card {
  position: relative;
  margin-top: 20px;
}

.card h2 {
  color: #333;
  padding: 16px 0;
}

.app-info p {
  color: #666;
  margin-bottom: 5px;
}

.option-header {
  font-weight: 500;
  color: #666;
  margin-bottom: 8px;
  font-size: 14px;
}

.question-card {
  margin-bottom: 16px;
  text-align: left;
  width: 100%;
  align-self: flex-start;
}

.question-card :deep(.ant-card-head) {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
}

.option-item {
  margin-bottom: 12px;
  padding: 8px;
  background-color: #f0f0f0;
  border-radius: 4px;
}

:deep(.ant-input-wrapper) {
  width: 100%;
}

:deep(.ant-page-header) {
  padding: 0;
}

.ant-space-vertical {
  width: 100%;
}

.ant-row {
  margin-top: 16px;
  gap: 12px;
}

.ant-col {
  flex: 1;
}

.ant-btn-sm {
  padding: 0 8px;
}
</style>
